const api = () => {
  return window.$api.message.contact
}
const apiMsg = () => { return window.$api.message.msg }
let chatTimer

import Vue from 'vue'
export default {
  namespaced: true,
  state: {
    hasNoReadChatList: false,
    chatList: [], // 聊天列表信息
    chatUserId: '',

    messageList: {}, // 消息集合

    systemMsgNum: 0

  },
  actions: {
    refreshChat({ commit, dispatch }) {
      if (!chatTimer) {
        chatTimer = setTimeout(async () => {
          chatTimer = null
          const list = (await window.$awaitWraper(api().getList())) || []
          list.forEach((item) => {
            dispatch("organization/user/load", { userIds: item.f_OtherUserId.split(','), isCache: true }, { root: true })
          })
          //console.log(list, 'refreshChat')
          commit("SET_CHATLIST", list)
          commit('SET_HASNOREADCHATLIST')
        }, 50)
      }
    },
    async removeChat({ commit }, chat) {
      commit('REMOVE_CHAT', chat.f_Id)
      commit('SET_HASNOREADCHATLIST')
      await api().remove(chat.f_Id)
    },
    revChatMsg({ commit, dispatch, state }, chat) {
      const myChat = state.chatList.find(
        t =>
          t.f_OtherUserId == chat.userId
      )

      if (myChat) {
        let num = myChat.f_NoReadNum + 1
        if (myChat.f_OtherUserId == state.chatUserId) {
          num = 0
        }
        Vue.set(myChat, 'f_NoReadNum', num)
        Vue.set(myChat, 'f_Content', chat.msg)
        Vue.set(myChat, 'f_Time', chat.dateTime)

        commit('ADD_MSG', {
          list: [{
            f_MsgId: chat.id,
            f_SendUserId: chat.userId,
            f_RecvUserId: chat.myUserId,
            f_Content: chat.msg,
            f_CreateDate: chat.dateTime,
          }], sendUserId: chat.userId
        })
        commit('SET_HASNOREADCHATLIST')
      }
      else {
        dispatch('refreshChat')
      }
    },
    async addChat({ dispatch, state }, chatList) {
      chatList.forEach(chat => {
        const myChat = state.chatList.find(
          t =>
            t.f_MyUserId == chat.f_MyUserId &&
            t.f_OtherUserId == chat.f_OtherUserId
        )
        if (!myChat) {
          chat.f_NoReadNum = 0
          chat.f_Content = ''
          chat.f_Time = window.$getDayTime()
          state.chatList.push(chat)
        }
      })
      await window.$awaitWraper(api().addList(chatList))
      await dispatch('refreshChat')
    },
    setChatUserId({ commit }, userId) {
      console.log(userId,'setChatUserId')
      commit('SET_CHATUSERID', userId)
      if (userId) {
        api().updateState(userId)
        commit('CLEAR_CHATNOREADNUM', userId)
        commit('SET_HASNOREADCHATLIST')
      }
    },


    async refreshMessage({ commit }, { recvUserId, sendUserId }) {
      const query = {
        rows: 30,
        page: 1,
        sidx: 'F_CreateDate DESC',
        toId: recvUserId,
        sendId: sendUserId
      }
      // 获取聊天记录
      const data = (await window.$awaitWraper(apiMsg().getPage(query))) || {}
      commit('ADD_MSG', { list: data.rows, sendUserId })
    },
    async sendMsg({ commit,state }, data) {
      commit('ADD_MSG', { list: [data], sendUserId: data.f_RecvUserId })
      data.f_MsgId = await window.$awaitWraper(apiMsg().add(data))

      const myChat = state.chatList.find(
        t =>
          t.f_OtherUserId == data.f_RecvUserId
      )
      if (myChat) {
        Vue.set(myChat, 'f_Content', data.f_Content)
        Vue.set(myChat, 'f_Time', data.f_CreateDate)
      }

      return data.f_MsgId;
    },

    async refreshSystemMsgNum({ commit }) {
      const num = await window.$awaitWraper(apiMsg().getSysNum())
      //console.log(num,'refreshSystemMsgNum')
      commit('SET_SYSTEMMSGNUM', num)
    }
  },
  mutations: {
    SET_CHATLIST: (state, list) => {
      state.chatList = list
    },
    REMOVE_CHAT(state, id) {
      state.chatList.splice(
        state.chatList.findIndex((t) => t.f_Id == id),
        1
      )
    },
    SET_HASNOREADCHATLIST: (state) => {
      if (state.chatList.findIndex(t => t.f_NoReadNum > 0 && t.f_OtherUserId != state.chatUserId) > -1) {
        state.hasNoReadChatList = true
      }
      else {
        state.hasNoReadChatList = false
      }
    },
    SET_CHATUSERID: (state, id) => {
      state.chatUserId = id
    },
    CLEAR_CHATNOREADNUM: (state, id) => {
      const myChat = state.chatList.find(
        t =>
          t.f_OtherUserId == id
      )
      if (myChat) {
        Vue.set(myChat, 'f_NoReadNum', 0)
      }
    },


    ADD_MSG(state, { list, sendUserId }) {
      if (list.length > 0) {
        const msgList = state.messageList[sendUserId] || []
        const addList = list.filter(t => msgList.findIndex(t2 => t.f_MsgId == t2.f_MsgId) == -1)
        msgList.push(...addList)
        Vue.set(state.messageList, sendUserId, msgList.sort((a, b) => { return Date.parse(a.f_CreateDate) - Date.parse(b.f_CreateDate) }))
      }
    },

    SET_SYSTEMMSGNUM(state, num) {
      state.systemMsgNum = num
    }
  }
}